import '../../styles.css'

import React, {useEffect, useState} from "react";
import Quiz from "@/pages/components/Quiz";
import redpacket from '../../../public/red.png'
import Image from "next/image";
import styles from './index.module.css'
import {useRouter} from "next/router";
import {audioDetail, queryUserInfo, submitAnswer, wxSign} from "@/service/api";
import CountDownModal from "@/pages/components/CountDownModal";
import {getDomain, LAST_PLAYBACK_TIME} from "@/utils";
import red_packet from "../../../public/share/red_packet.png";
import SubmitQuizParams = API.SubmitQuizParams;
import SubmitQuestionParams = API.SubmitQuestionParams;
import SubmitAnswerParams = API.SubmitAnswerParams;

declare var wx: any;

export default function Question() {
    const [showModal, setShowModal] = useState(false);
    const [showAudioModal, setShowAudioModal] = useState(false);
    const [showStopModal, setShowStopModal] = useState(false);

    const router = useRouter();
    const [audio, setAudio] = useState<any>({})
    const [selectedOptions, setSelectedOptions] = useState<any[]>([]); // 这里使用 any[] 来简化示例，你可以定义一个更精确的类型

    const wxUid = () => {
        return router.query.wxUid
    }
    const inviteId = () => {
        return router.query.inviteId
    }

    useEffect(() => {
        if (router.isReady) {
            const audioId = router.query.audioId
            localStorage.setItem(LAST_PLAYBACK_TIME + audioId, '0');

            // const wxUid = router.query.wxUid
            const params: API.AudioDetailParams = {
                audioId: audioId as string,
                wxGid: null,
                wxUid: wxUid() as string,
            }
            audioDetail(params).then(res => {
                console.log('audio detail', res)
                if (res.code === 1) {
                    setAudio(res.data)

                    //如果已经领取过红包，则不能答题，只能收听音频
                    if (res.data.quizStatus === 3) {
                        alert('已经领取过红包，不能重复答题')
                        window.location.href = '/audio?audioId=' + audioId + '&wxUid=' + wxUid()
                        return
                    }
                } else {
                    alert('获取音频详情失败,' + res.msg)
                }
            })
        }
    }, [router.isReady]);
    useEffect(() => {
        const script = document.createElement('script');
        script.src = "https://res.wx.qq.com/open/js/jweixin-1.6.0.js";
        script.onload = () => {
            console.log("微信JS-SDK加载完成")
            wxSign(window.location.href).then(res => {
                console.log('wx sign', res)
                wx.config({
                    // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: res.data.appId, // 必填，公众号的唯一标识
                    timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: [
                        'scanQRCode',
                        'checkJsApi',
                        'onMenuShareQQ',
                        'onMenuShareWeibo',
                        'onMenuShareQZone',
                        'getLocation',
                        'navigateToWeChat',
                        'navigateTo',
                        'onMenuShareAppMessage',
                        'onMenuShareTimeline',
                        'updateAppMessageShareData',
                        'updateTimelineShareData',
                    ] // 必填，需要使用的JS接口列表
                });
            })

            wx.ready(function () {
                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                queryUserInfo().then(res => {
                    if (res.code !== 1) {
                        alert('获取用户信息失败,' + res.msg)
                        return
                    }

                    const share_url = getDomain() + '/audio?audioId=' + audio.id + '&wxUid=' + router.query.wxUid + '&inviteId=' + res.data.unionid
                    wx.updateAppMessageShareData({
                        title: audio.name, // 分享标题
                        desc: '百余期奖励等您来领|' + router.query.wxUid, // 分享描述
                        link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: getDomain() + '/share/red_packet.png',// 分享图标
                        success: function () {
                            // 设置成功
                        }
                    })
                    wx.updateTimelineShareData({
                        title: audio.name, // 分享标题
                        link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: `${red_packet}`, // 分享图标
                        success: function () {
                            // 设置成功
                        }
                    })
                })
            });
            wx.error(function (res: any) {
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            });
        };
        document.body.appendChild(script);

        return () => {
            document.body.removeChild(script);
        };
    }, [audio]);

    const handleSelectChange = (options: any[], quizIndex: number) => {
        setSelectedOptions(prevState => {
            const newState = [...prevState];
            newState[quizIndex] = options;
            return newState;
        });
    };

    const submitAnswers = () => {
        const quizParams: SubmitQuizParams = {
            audioId: audio.id,
            questions: [],
        }
        selectedOptions.forEach((options, index) => {
            const question = audio.questions[index];
            const questionParams: SubmitQuestionParams = {
                id: question.id,
                questionName: question.questionName,
                answers: [],
            }
            options.forEach((option: any, idx: number) => {
                console.log(option)
                const answerParams: SubmitAnswerParams = {
                    isSelect: option.isSelected,
                    id: option.id,
                }
                if (option.isSelected) {
                    questionParams.answers.push(answerParams)
                }
            });
            quizParams.questions.push(questionParams)
        });
        console.log('quiz', quizParams)
        submitAnswer(quizParams).then(res => {
            console.log('submit answer res', res)
            if (res.code === 1) {
                if (res.data.correct) {
                    window.location.href = '/quiz_result?audioId=' + audio.id + '&wxUid=' + wxUid()
                } else {
                    if (res.data.answerCount === 1) {
                        setShowModal(true)
                    } else if (res.data.answerCount === 2) {
                        setShowAudioModal(true)
                    } else {
                        setShowStopModal(true)
                    }
                }
            } else {
                console.log('答题失败', res.msg)
                alert('答题失败,' + res.msg)
            }
        })
    }

    return (
        <>
            <div className={styles.redpacket_container}>
                <Image className={styles.redpacket} src={redpacket} alt={'红包'}/>
            </div>
            <div>
                {
                    audio.questions ? audio.questions.map((question: any, index: number) => (
                        <Quiz key={index} index={index} question={question} canSelect={true}
                              onSelectChange={(options) => handleSelectChange(options, index)}
                        />
                    )) : null
                }
            </div>
            <div className={styles.submit_container}>
                <button className={styles.submit} onClick={() => {
                    // setShowModal(true)
                    console.log('selectedOptions', selectedOptions)
                    submitAnswers()
                }}>提&nbsp;&nbsp;&nbsp;&nbsp;交
                </button>
            </div>
            {/*<Modal*/}
            {/*    className={styles.quiz_result}*/}
            {/*    isOpen={showModal}*/}
            {/*    onRequestClose={() => setShowModal(false)}*/}
            {/*    contentLabel="提示"*/}
            {/*>*/}
            {/*    <div className={styles.quiz_result_title}>答错<span className={styles.quiz_result_number}>1</span>次*/}
            {/*    </div>*/}
            {/*    <div className={styles.quiz_result_sub_title}>自动跳转重答</div>*/}
            {/*</Modal>*/}
            <CountDownModal isOpen={showModal} onClose={() => setShowModal(false)}
                            redirectTo={'/quiz?audioId=' + audio.id + '&wxUid=' + wxUid()}>
                <div className={styles.quiz_result_title}>答错<span className={styles.quiz_result_number}>1</span>次
                </div>
                <div className={styles.quiz_result_sub_title}>自动跳转重答</div>
            </CountDownModal>
            <CountDownModal isOpen={showAudioModal} onClose={() => setShowAudioModal(false)}
                            redirectTo={'/audio?audioId=' + audio.id + '&wxUid=' + wxUid()}>
                <div className={styles.quiz_result_title}>答错<span className={styles.quiz_result_number}>2</span>次
                </div>
                <div className={styles.quiz_result_sub_title}>请重新收听答题</div>
            </CountDownModal>
            <CountDownModal isOpen={showStopModal} onClose={() => setShowStopModal(false)}
                            redirectTo={'/audio?audioId=' + audio.id + '&wxUid=' + wxUid()}>
                <div className={styles.quiz_result_title}>答错<span className={styles.quiz_result_number}>3</span>次
                </div>
                <div className={styles.quiz_result_sub_title}>当前音频不能再答题了</div>
            </CountDownModal>
        </>
    )
}
